package www.wen.com.common.lib.util

import android.text.InputFilter
import android.text.Spanned
import www.wen.com.common.lib.extension.toast
import java.util.regex.Pattern

/**
 * @author WEN
 * @Description: EditText文字过滤工具类
 * @date 2021/10/14 12:12
 */
class InputFilterUtil {

    private val mFilters = mutableListOf<InputFilter>()

    /**
     * 排除表情
     */
    fun excludedExpression(
        isShowToast: Boolean = true,
        toastContent: String = "不支持输入表情",
        excludedAction: (() -> Unit)? = null
    ): InputFilterUtil {
        mFilters.add(object : InputFilter {
            var expression = Pattern.compile(
                "[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                Pattern.UNICODE_CASE or Pattern.CASE_INSENSITIVE
            )

            override fun filter(
                source: CharSequence,
                start: Int,
                end: Int,
                dest: Spanned,
                dstart: Int,
                dend: Int
            ): CharSequence? {
                val expressionMatcher = expression.matcher(source)
                return if (expressionMatcher.find()) {
                    if (isShowToast) {
                        toast(toastContent)
                    }
                    excludedAction?.invoke()
                    ""
                } else null
            }
        })
        return this
    }

    /**
     * 排除换行
     */
    fun excludedN(
        isShowToast: Boolean = true,
        toastContent: String = "不支持输入换行",
        excludedAction: (() -> Unit)? = null
    ): InputFilterUtil {
        mFilters.add(object : InputFilter {
            override fun filter(
                source: CharSequence,
                start: Int,
                end: Int,
                dest: Spanned,
                dstart: Int,
                dend: Int
            ): CharSequence? {
                return if (source.contains("\n") || source.contains("\r\n")) {
                    if (isShowToast) {
                        toast(toastContent)
                    }
                    excludedAction?.invoke()
                    ""
                } else null
            }
        })
        return this
    }

    /**
     * 排除换行
     */
    fun maxLength(
        length: Int
    ): InputFilterUtil {
        mFilters.add(InputFilter.LengthFilter(length))
        return this
    }

    fun build(): Array<InputFilter> = mFilters.toTypedArray()

}